﻿using Minecraft.BLL;
using Minecraft.BLL.mysql;
using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Config.Csv.CsvCom;
using Minecraft.Config.ipConst;
using Minecraft.Model;
using Minecraft.Model.Backpack;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minecraft.ServerHall.Cmd
{
	public class TestDirective : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Test_TestDirective;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<TestDirectiveReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：请求实体为空）" });
				return;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：未登录）" });
				return;
			}
			if (req.directiveStr.IsNullOrWhiteSpace())
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：directiveStr 参数为空）" });
				return;
			}

			var directiveList = req.directiveStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
			if (!directiveList.Any())
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：!directiveArr.Any()）" });
				return;
			}
			List<BackpackCellInfo> posGoodsinfoList = new List<BackpackCellInfo>();
			//添加操作影响的positionOptList
			List<BackpackGoodsPositionOpt> positionOptList = new List<BackpackGoodsPositionOpt>();

			switch (directiveList[0])
			{
				case "/give":
					{
						//指令格式：/give 物品id 数量 
						if (directiveList.Count() != 3)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：directiveList.Count() != 3）" });
							return;
						}
						var itemId = directiveList[1];
						var numStr = directiveList[2];
						int num = 0; int.TryParse(numStr, out num);
						if (num <= 0)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：num <= 0）" });
							return;
						}
						var isExists = session.IsExistItemsOrBlocks(itemId);
						if (!isExists)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：【{itemId}】不存在于物品表或者方块表中）" });
							return;
						}

						GiveGoods(session, itemId, num, positionOptList, out BaseResp baseResp);

						if (baseResp.RespLevel != RespLevelEnum.Success)
						{
							session.Send(defCommand, req, baseResp);
							return;
						}

						if (!positionOptList.Any())
						{
							baseResp = new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：背包满了）" };
							return;
						}

						//获取影响的位置列表
						positionOptList.ForEach(optItem =>
						{
							//找到受影响的物品位置信息
							posGoodsinfoList.AddRange(session.minecraftSessionInfo.goodsList.Where(m => m.enumGoodsBelongsToType_Convert == optItem.enumGoodsBelongsToType && m.GoodsPosition == optItem.GoodsPosition && m.guid == optItem.guid).GetBackpackGoodsCellInfo());
						});
					}
					break;
				default:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：暂不支持该指令【{directiveList[0]}】）" });
						return;
					}
					break;
			}


			var resp = new TestDirectiveResp
			{
				posGoodsinfoList = posGoodsinfoList
			};
			session.Send(defCommand, req, resp);
		}

		private static void GiveGoods(MinecraftSession session, string itemId, int num, List<BackpackGoodsPositionOpt> positionOptList, out BaseResp baseResp)
		{
			baseResp = new BaseResp();
			//将物品放入背包格子中
			var maxCount = session.GetMaxCellNumConvert(itemId);
			//if (maxCount < num)
			//{
			//	//session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：个数参数在配置表参数值之上）" });
			//	return;
			//}
			session.IsBackpackFull(out baseResp, out bool isFull, out List<BackpackGoodsItemInfo> canPlacedBpCellInfoList);
			if (baseResp.RespLevel != RespLevelEnum.Success)
			{
				//session.Send(defCommand, req, baseResp);
				return;
			}
			if (isFull) //背包已经满了
			{
				//baseResp = new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：背包满了）" };
				return;
			}
			//优先堆叠，再填空缺
			var bpGoodsItemInfo = canPlacedBpCellInfoList.FirstOrDefault(m => m.GoodsItemId == itemId);
			if (bpGoodsItemInfo == null)
			{
				bpGoodsItemInfo = canPlacedBpCellInfoList.FirstOrDefault(m => m.GoodsNum <= 0);
				if (bpGoodsItemInfo != null)
				{
					bpGoodsItemInfo.GoodsItemId = itemId;
				}
			}
			//背包中的指定格子还可以容纳多少个物品
			var canMoveCount = maxCount - bpGoodsItemInfo.GoodsNum;
			//得到实际可以插入的个数
			canMoveCount = Math.Min(canMoveCount, num);

			bpGoodsItemInfo.GoodsNum += canMoveCount;

			var goodsInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(m =>
			m.enumGoodsBelongsToType_Convert == bpGoodsItemInfo.enumGoodsBelongsToType
			&& m.GoodsPosition == bpGoodsItemInfo.GoodsPosition
			&& m.guid == bpGoodsItemInfo.guid);
			if (goodsInfo == null)
			{
				goodsInfo = new GoodsModel
				{
					BelongsTo = (int)bpGoodsItemInfo.enumGoodsBelongsToType,
					GoodsId = StringHelper.GetGuidStr(),
					GoodsItemId = bpGoodsItemInfo.GoodsItemId,
					GoodsPosition = bpGoodsItemInfo.GoodsPosition,
					guid = bpGoodsItemInfo.guid,
					Num = bpGoodsItemInfo.GoodsNum,
					PlayerId = session.minecraftSessionInfo.player.PlayerId,
					WastageValue = 100,
				};
				session.minecraftSessionInfo.goodsList.Add(goodsInfo);
			}
			else
			{
				goodsInfo.Num = bpGoodsItemInfo.GoodsNum;
			}
			if (!positionOptList.Any(m =>
				m.enumGoodsBelongsToType == goodsInfo.enumGoodsBelongsToType_Convert
				&& m.GoodsPosition == goodsInfo.GoodsPosition && m.guid == goodsInfo.guid))
			{
				positionOptList.Add(new BackpackGoodsPositionOpt
				{
					enumGoodsBelongsToType = goodsInfo.enumGoodsBelongsToType_Convert,
					GoodsPosition = goodsInfo.GoodsPosition,
					guid = goodsInfo.guid
				});
			}
			if (num - canMoveCount > 0)
			{
				GiveGoods(session, itemId, num - canMoveCount, positionOptList, out baseResp);
			}
		}
	}
}
